/**
 * 封装Axios全局拦截器
 *
 */

import axios, { AxiosInstance } from 'axios';
import nprogress from 'nprogress';
import Utils from '../Utils';
import config from '../../../default.config.json';

let HOST: string;

const env = process.env.NODE_ENV;
if (env === 'production') {
  HOST = config.host.production;
} else if (env === 'debug') {
  HOST = config.host.debug;
} else {
  HOST = config.host.development;
}

const agent: AxiosInstance = axios.create({
  baseURL: HOST,
  timeout: config.timeout,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Access-Token': Utils.session('user.token')
  }
});

// 请求拦截
// 添加请求过度滚动条
agent.interceptors.request.use(
  config => {
    nprogress.start();
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截
agent.interceptors.response.use(
  response => {
    nprogress.done();
    return response;
  },
  error => {
    nprogress.done();
    return Promise.reject(error);
  }
);

export default agent;
